package com.jadesoft.common;

import java.util.ArrayList;
import java.util.List;

import com.jadesoft.common.service.PaginationService;
import com.jadesoft.common.util.Constants;
import com.ufida.leaf.exception.BusinessException;

public class CommonBSImpl implements CommonBS {
	private PaginationService persistence = new PaginationService();
	
	/**
	 * 根据CODE获取档案列表
	 */
	public List queryByCode(Class clazz,Long enterId,String code){
		String hql = " from "+clazz.getName()+" where enterId = ? and code = ?";
		List args = new ArrayList();
		args.add(enterId);
		args.add(code);
		return persistence.query(hql, args.toArray());
	}
	
	/**
	 * 根据自定义列判断
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List query(Class clazz,Long enterId,String colunmName,String colunmValue){
		String hql = " from "+clazz.getName()+" where enterId = ? and "+ colunmName+" = ?";
		List args = new ArrayList();
		args.add(enterId);
		args.add(colunmValue);
		return persistence.query(hql, args.toArray());
	}
	
	
	/**
	 * 根据NO获取单据列表
	 */
	public Object queryByNo(Class clazz,Long enterId,String no){
		String hql = " from "+clazz.getName()+" where enterId = ? and no = ?";
		List args = new ArrayList();
		args.add(enterId);
		args.add(no);
		List list = persistence.query(hql, args.toArray());
		if(list.size()==0)
			throw new BusinessException("单据编号有误!");
		return list.get(0);
	}
	
	/**
	 * 判断编号是否已经存在
	 */
	public boolean isExists(Class clazz, Long enterId, String code) {
		return this.queryByCode(clazz, enterId, code).size()>0;
	}
	
	/**
	 * 判断自定义列是否已存在
	 */
	public boolean isExists(Class clazz, Long enterId, String propertyName,String propertyValue) {
		return this.query(clazz, enterId, propertyName,propertyValue).size()>0;
	}
	
	/**
	 * 获取相邻单据编号
	 */
	public String findAdjacentNo(Class clazz,
			Long enterId, String no, String direction) {
		String compareType = Constants.NEXT_BILL.equals(direction) ? " > " : " < ";
		String orderType = Constants.NEXT_BILL.equals(direction) ? " asc " : " desc ";
		String hql = " SELECT obj.no"   
					+ " FROM " + clazz.getName() + " obj "
					+ " WHERE obj.enterId = ? "
					+ " AND  obj.no" + compareType + " ? " 
					+ " ORDER BY obj.no" + orderType ;
		List params = new ArrayList();
		params.add(enterId);
		params.add(no);
		Object obj = persistence.queryFirst(hql, params.toArray());
		return obj == null ? null : obj.toString();
	}
	
	public static void main(String[] args) {
		
	}

}
